/**
 * ExpressionTree.java
 * 
 * Copyright (C) 2012 - Thibault BUREL
 * 
 * This file is part of MathDraft.
 *
 * MathDraft is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * MathDraft is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MathDraft.  If not, see <http://www.gnu.org/licenses/>
 *  
 */
package drk.mathdraft.ihm.tree;

import drk.mathdraft.StudiedProposition;
import drk.mathdraft.proposition.*;

import java.awt.*;
import java.util.Observable;
import java.util.Observer;

import javax.swing.*;
import javax.swing.tree.*;

public class ExpressionTree extends JPanel implements Observer
{
	private static final long serialVersionUID = 1L;

	protected JTree tree;
	
	public ExpressionTree()
	{
		StudiedProposition st = StudiedProposition.getInstance();
		
		this.tree = new JTree(new DefaultTreeModel
			(populateTree(st.getProposition())));
		
		this.tree.setPreferredSize(new Dimension(250,480));
		
		this.add(tree);
		this.tree.setCellRenderer(new TreeIconRenderer());
		st.addObserver(this);
	}
	
	public Proposition getSelectedNode()
	{
		return ((TreeNode)((DefaultMutableTreeNode)this.tree.getLastSelectedPathComponent()).getUserObject()).propositionNode;
	}
	
	protected DefaultMutableTreeNode populateTree (Proposition e)
	{
		DefaultMutableTreeNode newNode
			= new DefaultMutableTreeNode ("DefaultEmptyNode");
		
		if(e != null)
		{
			newNode = new DefaultMutableTreeNode(new TreeNode(e));
			
			if(e.getFirstChild() != null)
			{
				newNode.add(populateTree(e.getFirstChild()));
				
				// Go through child
				Proposition currentChild = e.getNextChild(e.getFirstChild());
				while(currentChild != null)
				{
					newNode.add(populateTree(currentChild));
					currentChild = e.getNextChild(currentChild);
				}
			}
		}
		
		return newNode;
	}
	
	public void update(Observable o, Object arg)
	{
		this.tree.setModel(new DefaultTreeModel(populateTree(StudiedProposition.getInstance().getProposition())));
		repaint();
	}
}